package com.nti56.springboot.controller;


import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.github.pagehelper.util.StringUtil;
import com.nti56.springboot.model.Module;
import com.nti56.springboot.model.User;
import com.nti56.springboot.service.ModuleService;
import com.nti56.springboot.service.UserService;
import com.nti56.springboot.utils.Constant;
import com.nti56.springboot.utils.MD5Util;
import com.nti56.springboot.utils.ParamUtil;
 

/**
 * @author Administrator
 *
 */
@RequestMapping( value = "/system", method = RequestMethod.GET)
@Controller
public class SystemController {
	
	private static final Logger logger = LoggerFactory.getLogger(SystemController.class);

	
	@Autowired
    private ModuleService moduleService;
	
	@Autowired
    private UserService userService;
	
	@RequestMapping(value="/login")
    public String login(HttpServletRequest request )  
    {
    	return "login";
    }
	
	@RequestMapping(value="/index")
    public String index(HttpServletRequest request )  
    {
    	return "index";
    }
	
	@RequestMapping(value="/403")
    public String er403(HttpServletRequest request )  
    {
		logger.info("----未授权的页面---");
		return "403";
    }
	
	@RequestMapping(value="/404")
    public String er404(HttpServletRequest request )  
    {
		logger.info("----找不到该页面---");
		return "404.html";
    }
	
	@RequestMapping(value="/toPortal")
	public String toPortal() {
		return "portal";
	}
	
	// 登录提交地址和applicationontext-shiro.xml配置的loginurl一致。 (配置文件方式的说法)  
    @RequestMapping(value="/loginAuth",method=RequestMethod.POST)  
    public String loginAuth(HttpServletRequest request,String userName,String password,
    		boolean rememberMe,HttpSession session) throws Exception {  
    	logger.debug("SystemController.login()---"); 
    	if(StringUtil.isEmpty(userName) && StringUtil.isEmpty(password)) {
    		return "login";
    	}
        if(StringUtil.isEmpty(userName)){
        	request.setAttribute("msg", "用户名不能为空！");
        	return "login";  
        }
        if(StringUtil.isEmpty(password)){
        	request.setAttribute("msg", "密码不能为空！");
        	return "login";  
        }
       // 登录失败从request中获取shiro处理的异常信息。  
       // shiroLoginFailure:就是shiro异常类的全类名.
        UsernamePasswordToken token = new UsernamePasswordToken(userName, MD5Util.MD5(password),rememberMe);
        Subject currentUser =  SecurityUtils.getSubject();
        try {
        	currentUser.login(token);   //完成登录         
        } catch (UnknownAccountException ex) { 
        	logger.error(ex.getMessage(),ex);
        	request.setAttribute("msg", "用户不存在或者密码错误！");           
        } catch (IncorrectCredentialsException ex) { 
        	logger.error(ex.getMessage(),ex);
        	request.setAttribute("msg", "用户不存在或者密码错误！");           
        } catch (AuthenticationException ex) {
        	logger.error(ex.getMessage(),ex);
        	request.setAttribute("msg", ex.getMessage());        
        } catch (Exception ex) {  
        	logger.error(ex.getMessage(),ex);
            request.setAttribute("msg", "内部错误，请重试！");     
        }  
        //验证是否登录成功
        if(currentUser.isAuthenticated()){
        	User user=(User) currentUser.getPrincipal();
            session.setAttribute(Constant.SESSION_USER_KEY, getCompleteUser(user));
            List<Module> authAccordions = this.findAuthAccordion(user.getUserId());
            List<Module> authUrls = this.findAuthUrl(user.getUserId());
            List<String> authOrgCodes = this.findAuthOrg(user.getUserId());
            session.setAttribute(Constant.SESSION_USER_AUTH_URL, authUrls);
            session.setAttribute(Constant.SESSION_USER_AUTH_ACCORDION, authAccordions);
            session.setAttribute(Constant.SESSION_USER_DATA_ORG, authOrgCodes);
            return "index"; 
        }else{
        	token.clear();
        	return "login";  
        }
    }  
	
    /**
     * 重新查询一次，把完整的用户信息，user, employee,org信息查询出来
     * 原来的user只是单纯的tb_user表信息，懒的修改查询SQL了
     * @param user
     * @return
     */
    private User getCompleteUser(User user){
    	return userService.getById(user.getUserId());
    }
    
    
    @RequestMapping("/logOut")
    public String logOut(HttpSession session) {
    	session.removeAttribute(Constant.SESSION_USER_KEY);
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        return "login";
    }
    
    /**
     * 根据用户ID，获取用户授权资源 (左侧url菜单)
     * @param userId
     * @return
     */
    private List<Module> findAuthUrl(String userId){
    	Map map = ParamUtil.setParam("userId", userId);
    	map.put("moduleTypeNotEq", Constant.RESOURCE_TYPE_BUTTON);
    	map.put("roleType", Constant.SYS_ROLE_TYPE_OPERATE);
    	return moduleService.findAuthResource(map);
    }
    
    /**
     * 根据用户ID，获取用户授权资源 (左侧Accordion菜单)
     * @param userId
     * @return
     */
    private List<Module> findAuthAccordion(String userId){
    	Map map = ParamUtil.setParam("userId", userId);
    	map.put("moduleType", Constant.RESOURCE_TYPE_ACCORDION);
    	map.put("roleType", Constant.SYS_ROLE_TYPE_OPERATE);
    	return moduleService.findAuthResource(map);
    } 
    
    private List<String> findAuthOrg(String userId) {
    	return moduleService.getDataAuthOrgCodeList(userId);
    }
}
